// pages/category/index.js
import { request } from "../../request/index";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 左边菜单数据
    leftMenuList: [],
    // 右边内容数据
    rightContentList: [],
    // 被点击的左侧的菜单
    currentIndex: 0,
  },

  Cates: [],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取本地存储数据
    const Cates = wx.getStorageSync("cates");
    console.log("time =====>  " + Cates.time);

    if (
      !Cates ||
      !Cates.data ||
      Cates.data.length === 0 ||
      Date.now() - Cates.time > 1000 * 60 * 60
    ) {
      this.getCategoryMenu();
    } else {
      this.Cates = Cates.data;
      let leftMenuList = this.Cates.map((v) => {
        return v.cat_name;
      });
      let rightContentList = this.Cates[0].children;
      this.setData({
        leftMenuList: leftMenuList,
        rightContentList: rightContentList,
      });
    }
  },

  /* 获取分类菜单 */
  getCategoryMenu() {
    request({
      url: "https://api-hmugo-web.itheima.net/api/public/v1/categories",
    }).then((result) => {
      this.Cates = result.data.message;
      wx.setStorageSync("cates", { time: Date.now(), data: this.Cates });
      // this.setData({
      //   categoryList: result.data.message,
      // });
      let leftMenuList = this.Cates.map((v) => {
        return v.cat_name;
      });
      let rightContentList = this.Cates[0].children;
      this.setData({
        leftMenuList: leftMenuList,
        rightContentList: rightContentList,
      });
    });
  },

  bindCategory(e) {
    let index = e.currentTarget.dataset.index;
    let rightContentList = this.Cates[index].children;
    this.setData({
      rightContentList: rightContentList,
      currentIndex: index,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
